from influxdb_client import InfluxDBClient
import pandas as pd
import json
import configparser

# 创建 ConfigParser 对象
config = configparser.ConfigParser()

# 读取配置文件
config.read('config.ini')

class InfluxDBDataFetcher:
    def __init__(self, url, token, org, bucket):
        self.client = InfluxDBClient(url=url, token=token, org=org)
        self.bucket = bucket

    def get_odds_data(self, match_id):
        query = f'''
        from(bucket: "{self.bucket}")
          |> range(start: 0)
          |> filter(fn: (r) => r["_measurement"] == "odds")
          |> filter(fn: (r) => r["_field"] == "odds")
          |> filter(fn: (r) => r["team"] == "{match_id}" )
          |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")
          |> sort(columns: ["_time"], desc: false)  // 按时间升序排序
          |> yield(name: "all_data")
        '''

        result = self.client.query_api().query_data_frame(query)
        if result.empty:
            print(f"查询结果为空，可能没有符合条件的数据（队伍: {match_id}）")
            return pd.DataFrame()  # 返回空的 DataFrame 以防报错

        # 删除不需要的列
        data = result.drop(columns=["result", "table", "_start", "_stop", "_measurement"], errors='ignore')
        # 将时间列设为索引
        data.set_index("_time", inplace=True)
        
        # 只保留前120个点位
        return data.head(180)

def load_matches_from_json(file_path):
    # 从 JSON 文件中加载比赛配置
    with open(file_path, 'r', encoding='utf-8') as f:
        matches = json.load(f)
    return matches

def main():
    # InfluxDB 配置
    url = config['influxdb']['url']
    token = config['influxdb']['token']
    org = config['influxdb']['org']
    bucket = config['influxdb']['bucket']

    # 比赛配置
    matches = load_matches_from_json('matches_config.json')
    # matches = [
    #     {'team1_id': '38030929-r1-Xtreme Gaming', 'team2_id': '38030929-r1-Talon Esports', 'match_label': 'team1'},
    #     {'team1_id': '38030929-r2-Xtreme Gaming', 'team2_id': '38030929-r2-Talon Esports', 'match_label': 'team1'},

    #     # 添加更多比赛配置...
    # ]

    # 数据存储
    all_data = []

    fetcher = InfluxDBDataFetcher(url, token, org, bucket)

    for match in matches:
        team1_data = fetcher.get_odds_data(match['team1_id'])
        team2_data = fetcher.get_odds_data(match['team2_id'])

        if len(team1_data) < 180 or len(team2_data) < 180:
            print(f"数据不足，无法进行进一步处理（比赛: {match['team1_id']} vs {match['team2_id']}）")
            continue

        # 提取赔率值
        team1_odds = team1_data['odds'].values[:180]
        team2_odds = team2_data['odds'].values[:180]
        
        # 创建 DataFrame，列名为 A1, A2, ..., A180, B1, B2, ..., B180
        columns = [f'A{i+1}' for i in range(180)] + [f'B{i+1}' for i in range(180)] + ['match_label']

        # 创建包含两只队伍赔率的行，附带胜负标签
        row = list(team1_odds) + list(team2_odds) + [match['match_label']]
        all_data.append(row)

    # 创建包含所有比赛的数据的 DataFrame
    df = pd.DataFrame(all_data, columns=columns)

    # 将数据写入 CSV
    df.to_csv('matches_odds.csv', index=False)
    print("所有数据已写入 matches_odds.csv")


if __name__ == "__main__":
    main()
